package com.dreamchaser.familydevice.controller.wechart;


import com.dreamchaser.familydevice.service.impl.WxDeviceHandle;
import com.dreamchaser.familydevice.util.QYWeChat.WeChatUtil;
import com.dreamchaser.familydevice.util.QYWeChat.qq.weixin.mp.aes.AesException;
import com.dreamchaser.familydevice.util.QYWeChat.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.dreamchaser.familydevice.util.QYWeChat.service.impl.QYWeChatNewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("QYWechat")
@Slf4j
public class ValidateController {

    @Autowired
    WeChatUtil weChatUtil;
    @Autowired
    WxDeviceHandle wxDeviceHandle;

    /**
     * 验证数据，并返回微信验证
     *
     * @param request
     * @param response
     * @param token
     * @param encodingAesKey
     * @param receiveid
     * @return
     */
    public String getValidate(HttpServletRequest request, HttpServletResponse response, String token, String encodingAesKey, String receiveid) {
        // 微信加密签名
        String msg_signature = request.getParameter("msg_signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        System.out.println("request=" + request.getRequestURL());
        String result = null;
        // 通过检验msg_signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        try {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAesKey, receiveid);
            result = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr);
            return result;
        } catch (Exception e) {
            return "检验异常，" + e.getMessage();
        }
    }

    /**
     * 验证数据，并返回消息内容
     *
     * @param request
     * @param response
     * @param token
     * @param encodingAesKey
     * @param receiveid
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String getContent(HttpServletRequest request, HttpServletResponse response, String token, String encodingAesKey, String receiveid) throws ServletException, IOException {
        // 微信加密签名
        String msg_signature = request.getParameter("msg_signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");

        System.out.println("request=" + request.getRequestURL());

        //region 获取请求体内容
        StringBuffer sb = new StringBuffer();
        InputStream is = request.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String s = "";
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }
        String echostr = sb.toString();
        //end region


        // 通过检验msg_signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        String content = null;
        try {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAesKey, receiveid);
            content = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, echostr);
            return content;
        } catch (AesException e) {
            weChatUtil.sendAgentMsg("ShaJun|ShaJie", WeChatUtil.bugAgentId, e.getMessage() + e.getStackTrace().toString());
        }
        return content;
    }

    //region 测试联调

    /**
     * 确认请求来自微信服务器( 测试)
     */
    @GetMapping("/validate")
    public void validate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        String result = getValidate(request, response, "ray", "z2W9lyOAR1XjY8mopEmiSqib0TlBZzCFiCLp6IdS2Iv", "ww973d3e6796db49c7");
        if (result == null) {
            result = "ray";
        }
        out.print(result);
        out.close();
        out = null;
    }

    /**
     * 确认收到微信推送消息并实现逻辑(测试)
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @PostMapping("/validate")
    public void receive(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String content = getContent(request, response, "ray", "z2W9lyOAR1XjY8mopEmiSqib0TlBZzCFiCLp6IdS2Iv", "ww973d3e6796db49c7");
        PrintWriter out = response.getWriter();
        //if (content != null) new QYWeChatNewsService().sendMessage(content, weChatUtil);
        out.print(content);
        out.close();
        out = null;
    }

    //endregion

    //region 具体应用推送地址(复制测试 代码更改配置即可)

    /**
     * 设备应用验证
     */
    @GetMapping("/device")
    public void hxwValidate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        String result = getValidate(request, response, "device", "z2W9lyOAR1XjY8mopEmiSqib0TlBZzCFiCLp6IdS2Iv", "ww973d3e6796db49c7");
        if (result == null) {
            result = "ray";
        }
        out.print(result);
        out.close();
        out = null;
    }

    /**
     * 应用推送消息
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @PostMapping("/device")
    public void hxwReceive(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("微信推送");
        String content = getContent(request, response, "device", "z2W9lyOAR1XjY8mopEmiSqib0TlBZzCFiCLp6IdS2Iv", "ww973d3e6796db49c7");
        PrintWriter out = response.getWriter();
        log.info(content);
        if (content != null) {
            try{
                new QYWeChatNewsService(wxDeviceHandle).sendMessage(content, weChatUtil);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        out.print(content);
        out.close();
        out = null;
    }
    //endregion
}
